package org.yxjme.exjni_two.u;


import org.yxjme.exjni_two.i.CallBack;

import java.util.Timer;
import java.util.TimerTask;

public class TimerCountUtil {


    private Timer timer ;
    private MyTimerTask timerTask ;
    private int seconds ;
    private boolean isPause ;
    private CallBack callBack ;


    public TimerCountUtil(){
        timer = new Timer() ;
        timerTask = new MyTimerTask();
    }


    /**
     * 回调
     *
     * @param callBack
     * @return
     */
    public TimerCountUtil setCallBack(CallBack callBack) {
        this.callBack = callBack;
        return TimerCountUtil.this ;
    }



    /**
     * 開始倒计时
     */
    public void start(){
        if (timer!=null){
            timer.schedule(timerTask,1000,1000);
        }
    }



    /**
     * 暂停倒计时
     *
     * @param isPause
     */
    public TimerCountUtil setPause(boolean isPause){
        this.isPause=isPause;
        return this;
    }




    private class MyTimerTask extends TimerTask{

        @Override
        public void run() {
            if (!isPause){
                ++ seconds;
                if (callBack!=null){
                    callBack.onResult(formatTime());
                }
            }
        }
    }


    /**
     * 格式化时间
     */
    private String formatTime(){
        /*小时*/
        int h = seconds/3600;
        /*提取小时之后得到剩下的秒数*/
        int tempM = seconds % 3600 ;
        /*分钟*/
        int m = tempM / 60 ;
        /*剩下的秒钟*/
        int s = tempM  % 60 ;

        String h1;
        String m1;
        String s1;
        if (h<9){
            h1 = "0"+h;
        }else {
            h1 = ""+h;
        }

        if (m<9){
            m1 = "0"+m;
        }else {
            m1 = ""+m;
        }


        if (s<9){
            s1 = "0"+s;
        }else {
            s1 = ""+s;
        }

        /**/
        String time = "%s:%s:%s";
        return String.format(time,h1,m1,s1);
    }



    /**
     * 重置释放
     *
     */
    public TimerCountUtil release(){

        if (timer!=null){
            timer.cancel();
            timer = null ;
        }


        if (timerTask!=null){
            timerTask.cancel();
            timerTask = null ;
        }

        seconds = 0 ;

        if (callBack!=null){
            callBack.onResult(formatTime());
        }
        return this ;
    }
}
